package com.liuyucheng.idea_springboot.shirojwt;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liuyucheng.idea_springboot.bean.LycUser;
import com.liuyucheng.idea_springboot.bean.Result;
import com.liuyucheng.idea_springboot.bean.User;
import com.liuyucheng.idea_springboot.dao.LycUserMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户登录控制层
 */
@RestController
//@RequestMapping("/user")
public class LoginController {

    @Resource
    private LycUserMapper lycUserMapper;

    /**
     * 用户登录
     * @param lycUser 用户提交信息
     * @return 结果
     */
    @PostMapping("/login")
    public Result<Object> login(@RequestBody LycUser lycUser) {
//        String realPassword = userMapper.getPassword(username);
        String username = lycUser.getUsername();
        String password = lycUser.getPassword();
        // 查询数据库
        LycUser dbUser = lycUserMapper.selectOne(
                new QueryWrapper<LycUser>()
                        .eq("username",username).last("limit 1")
        );
        if(dbUser==null){
            return new Result<>(401,"用户名不存在",null);
        }
        String realPassword = dbUser.getPassword();

        if (!realPassword.equals(password)) {
            return new Result<>(401,"密码错误",null);
        } else {
            return new Result<>(200,"登录成功",JWTUtil.createToken(username));
        }
    }

    /**
     * 没有权限时的响应
     * @param message 信息
     * @return 结果
     */
    @PostMapping(path = "/unauthorized/{message}")
    public Result<Object> unauthorized(@PathVariable("message") String message) {
        return new Result<>(403,message,null);
    }
}
